<!-- 巡检点位 -->
<template>
	<div class="zs-table-page-container">
		<!-- 查询条件 -->
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-input v-model="queryParams.pointName" class="zs-select-md zs-space-right-sm" placeholder="点位名称" clearable @blur="queryList" />
				<el-input v-model="queryParams.pointNum" class="zs-select-md zs-space-right-sm" placeholder="点位编号" clearable @blur="queryList" />
				<el-select v-model="queryParams.pointFloorNum" class="zs-select-md zs-space-right-sm" placeholder="点位楼层" clearable @change="queryList">
					<el-option v-for="item in dictObj.BUILDING_LEVEL" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.effectiveState }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.pointType" class="zs-select-md zs-space-right-sm" placeholder="关联类型" clearable @change="queryList" :teleported="false">
							<el-option v-for="item in pointList" :key="item.id" :label="item.dicName" :value="item.id" />
						</el-select>
						<el-select placeholder="生效状态" v-model="queryParams.effectiveState" class="zs-select-md zs-space-right-sm" @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.VALIDATE_FLAG" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList" v-btnPermi="{ permis: ['p_btn_property_point_list_query'] }"> 查询 </el-button>
			</span>
			<span>
				<el-button class="zs-btn-plain zs-btn-md" @click="batchDownload">批量下载</el-button>
				<el-button class="zs-btn-md zs-btn-primary" :disabled="route.query.pageType == 'edit' ? false : true" @click="openDrawer(false, 'add', {}, 'base')" v-btnPermi="{ permis: ['p_btn_property_point_list_add'], businessFlag: true }">新增</el-button>
			</span>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" align="center" :index="(index) => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="pointName" label="点位名称" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="pointNum" label="点位编号" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="pointFloorNum" label="点位楼层" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="pointTypeName" label="点位类型" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="name" label="设备设施名称" width="110" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="inventoryName" label="清单名称" align="center" :formatter="defaultTableData" />
				<el-table-column prop="effectiveState" label="生效状态" align="center">
					<template #default="{ row }">
						<span :class="row.effectiveState == 1 ? 'zs-validata-status-yes' : 'zs-validata-status-no'">{{ row.effectiveState == 1 ? '有效' : '失效' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="审核状态" align="center">
					<template #default="scope">
						<div :class="{ 'zs-approval-status-yes': scope.row.auditStatus == 1, 'zs-approval-status-no': scope.row.auditStatus == 0, 'zs-approval-status-wait': scope.row.auditStatus == null || scope.row.auditStatus == '' }">
							{{ getDictoryTxt('AUDIT_STATUS', scope.row.auditStatus) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="定义" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(true, 'info', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_point_list_view'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_point_list_edit'], businessFlag: true }">编辑</el-button>
					</template>
				</el-table-column>
				<el-table-column label="二维码" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="qrCodeDownload(row)" v-btnPermi="{ permis: ['p_btn_property_point_list_qrcode_download'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="downloadFn(row)">下载</el-button>
					</template>
				</el-table-column>
				<el-table-column label="巡检记录" width="90" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="goRecordPage(row, 'check')" v-btnPermi="{ permis: ['p_btn_property_point_list_record_query'] }">{{ row.inspectionRecordNum + '条' }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="formatLastInspectionTime" width="120" label="最近巡检" align="left" :formatter="defaultTableData" />
				<el-table-column label="巡检距今" align="left">
					<template #default="{ row }">
						<span>{{ row.beforePresentDay ? row.beforePresentDay + '天' : '-' }}</span>
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>

	<!-- 点位信息 -->
	<DrawerPoint ref="pointRef" :isShow="drawer.base.isShowDrawer" :pointList="pointList" :isReadOnly="drawer.base.isReadOnly" :handleType="drawer.base.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'base')"> </DrawerPoint>

	<!-- 二维码 -->
	<DialogQrCode ref="qrcodeRef" :currentRow="currentRow.data"></DialogQrCode>
</template>

<script setup>
	import DrawerPoint from './components/drawerPoint.vue';
	import DialogQrCode from './components/dialogQrCode.vue';
	import { inspectListApi, batchDownloadApi } from '@/api/inspect.js';
	import { getDictoryApi } from '@/api/common.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute, useRouter } from 'vue-router';
	import { defaultTableData, getDictoryTxt, parseTime, deepClone, downloadNewFile } from '@/utils/publicUtils';

	const router = useRouter();
	const route = useRoute();
	let store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'BUILDING_LEVEL']);
	const projectName = ref(decodeURI(route.query.projectName));

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNumber: 1, pageSize: curPageSize.value, effectiveState: '1' });

	// 抽屉相关
	let currentRow = reactive({ data: {} });
	let drawer = reactive({
		base: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		}
	});

	const openDrawer = (flag, handleType, row, drawerType) => {
		drawer[drawerType].isReadOnly = flag;
		drawer[drawerType].isShowDrawer = true;
		drawer[drawerType].handleType = handleType;
		currentRow.data = row;
	};

	const closeDrawer = (data, drawerType) => {
		drawer[drawerType].isShowDrawer = data.isShow;
		data.isRefresh && queryList('init');
	};

	// 物业字典
	let pointList = ref([]);
	const getDictory = async () => {
		let res = await getDictoryApi({ sort: true, delFalg: 0 });
		if (res.data.code !== 200) return;
		pointList.value = res.data.data.POINT_TYPE || [];
	};

	// 列表数据源
	const queryList = async init => {
		if (process.env.NODE_ENV !== 'development') {
			let portalResourceList = JSON.parse(localStorage.getItem('portalResourceList'));
			if (init != 'init' && !portalResourceList.includes('p_btn_property_point_list_query')) return;
		}
		tableData.loading = true;
		let res = await inspectListApi(queryParams);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			item.formatLastInspectionTime = parseTime(item.lastInspectionTime, '{y}-{m}-{d}') || '-';
		});
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNumber = size;
		}
		queryList('init');
	};

	//二维码
	const qrcodeRef = ref();
	const qrCodeDownload = async row => {
		if (!row.url) {
			ElMessage.warning('暂无二维码');
			return;
		}
		currentRow.data = row;
		qrcodeRef.value.dialogShow = true;
	};

	//二维码下载
	const downloadFn = data => {
		if (!data.url) {
			ElMessage.warning('暂无二维码');
			return;
		}
		let splitList = data.url.split('.');
		let suffix = splitList[splitList.length - 1];
		const customName = `【${data.pointName}】【${data.pointNum}】.${suffix}`;
		fetch(data.url)
			.then(response => response.blob())
			.then(blob => {
				const a = document.createElement('a');
				a.href = URL.createObjectURL(blob);
				a.download = customName;
				a.click();
			})
			.catch(error => console.error('下载图片时出现错误：', error));
	};

	//二维码批量下载
	const batchDownload = async() => {
		let params = deepClone(queryParams)
		delete params.pageNumber
		delete params.pageSize
		batchDownloadApi(params).then(res => {
			downloadNewFile(res.data, `【${projectName.value}】点位二维码.zip`);
		});
	};

	// 巡检记录
	const goRecordPage = (row, type) => {
		router.push({ path: '/page/routeController/index', query: { rid: 'recordMaintain', rTitle: '巡检记录', id: row.id, pageType: 'point', funType: type } });
	};

	getDictory();
	queryList('init');
</script>
